<?php

class User_AuthController extends Custom_Controller_Action
{
    private $_layout    = '';
    private $_module_ini    = '';

    public function init()
    {
        /* Initialize action controller here */
        $this->_layout = Zend_Layout::getMvcInstance();
		$this->_layout->setLayout('layout');
    }

    public function loginAction()
    {
        $form = new User_Form_Login();
        $this->view->form = $form;
		
        $user = new User_Model_DbTable_User();

        if($this->getRequest()->isPost())
        {
            $formData = $this->getRequest()->getPost();
			
            if($form->isValid($formData))
            {
                 if ($user->processLogin($form->getValues(),$this->_module_ini))
                 {
                    // We're authenticated! Redirect to the home page
                    $this->RedirectUrl('/user/dashboard');
                 }
                 else
                 {
                    $this->view->msg = __("Invalid Email or password");
                 }

            }
        }
    }

    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->Redirector('login'); // back to login page

    }

	public function forgetpasswordAction()
	{
		$form = new User_Form_ForgetPassword();
        $this->view->form = $form;

        if($this->getRequest()->isPost())
        {
            $formData = $this->getRequest()->getPost();

            if($form->isValid($formData))
            {
				#get user
				$user = new User_Model_DbTable_User();
				$userinfo = $user->getByColumn('email',$formData['email']);
				
				if($userinfo)
				{
					#Generate token and update user
					$token = Custom_General::randomString(30);
					$data = array('password_reset_token' => $token.":".time());
					$user->updateById($data,$userinfo[0]['id']);
					#Prepare email template data
					$data['name'] = $userinfo[0]['first_name']." ".$userinfo[0]['last_name'];
					$data['reset_link'] = $this->_site_url."/user/auth/resetpassword/email/".$userinfo[0]['email']."/token/".$token;

					#Parse html template files
					$config = new Zend_Config_Ini(APPLICATION_PATH.'/configs/config.ini','general');
					$lang = Zend_Registry::get('translate');
					$template = APPLICATION_PATH .'/layouts/email_templates'. DS .$lang->getLocale(). DS .'forget_password.html';
					
					#Send email
					$mail	= new Custom_Mail();
					$content = $mail->parseHtml($template, $data);
					$mail->setSubject(__($this->Config->params->forgetPasswordSubject));
					$mail->setBodyHtml($content);
					$mail->addTo($userinfo[0]['email'], $userinfo[0]['first_name']);

					if($mail->send())
					{
						$this->addMessage('New Password is sent to your email.');
					}
					else
					{
						$this->addMessage('There is problem for sending email','error');
					}
				}
				else
				{
					$this->addMessage('Email address not found','error');
				}
			}
        }
	}

	public function resetpasswordAction()
	{
		$is_invalid_link = true;

		$token = $this->getRequest()->getParam('token');
		$email = $this->getRequest()->getParam('email');
		#find user by token
		if($token && $email)
		{
			$user		= new User_Model_DbTable_User();
			$userinfo	= $user->getByColumn('email',$email);

			$db_token	= $userinfo[0]['password_reset_token'];
			$tokens		= explode(':',$db_token);
			$config = new Zend_Config_Ini(APPLICATION_PATH.'/configs/config.ini','general');
			
			if($userinfo && $token == $tokens[0] && (time()-$tokens[1]) < ($this->Config->params->tokenExpire*60*60))
			{
				$reset_form = new User_Form_ResetPassword();
				$this->view->form = $reset_form;

				if($this->getRequest()->isPost())
				{
					$formData = $this->getRequest()->getPost();

					if($reset_form->isValid($formData))
					{
						$data['password'] = Custom_General::encrypt($formData['password']);
						$data['password_reset_token'] = '';
						$user->updateById($data, $userinfo[0][id]);
						$this->addMessage('Password reset successfully');
						$this->Redirecto('/user/login');
					}
				}

				$is_invalid_link = false;
			}
		}

		if($is_invalid_link)
		{
			$this->addMessage('Invalid password reset link','error');
			$this->_forward('access', 'error','default');
		}
	}
}

